package org.fuxia.im.listeners;

import java.awt.Component;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.SwingUtilities;

import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.common.CommonDialog;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.listeners.Listener;
import org.fuxia.im.core.utils.ObjectUtil;
import org.fuxia.im.gui.FindFriend;

import com.alibaba.fastjson.JSONArray;

public class QueryResultListener implements Listener
{

	public void trigger(Object param)
	{
		ECResponse resp = (ECResponse) param;
		Component parent = null;
		Object currentReq = ClientContext
				.removeKey(ClientConst.CURRENT_REQUESTOR);
		if (currentReq != null)
		{
			parent = (Component) currentReq;
		}
		Object waitDialog = ClientContext
				.removeKey(ClientConst.CURRENT_WAITING_DIALOG);
		if (waitDialog != null)
		{
			JDialog dialog = (JDialog) waitDialog;
			//dialog.setVisible(false);
			dialog.dispose();
		}
		if (resp.getStatusCode() == null || resp.getStatusCode() != 200)
		{
			CommonDialog.showErrorMessageDialog(parent, resp.getResponseText());
			return;
		}
		handlerSuccess(resp, parent);
	}

	@SuppressWarnings("unchecked")
	private void handlerSuccess(final ECResponse resp , Component current)
	{
		final FindFriend frame = (FindFriend) current;
		if(resp.getResponseType().equals("query_result")) {
			SwingUtilities.invokeLater(new Runnable() {
				
				public void run() {
					try
					{
						final List<Object[]> result = ObjectUtil.getObjectByJson(resp.get("qresult").toString(), List.class);
						frame.addUsers(result);
					}
					catch (Exception e)
					{
						CommonDialog.showErrorMessageDialog(frame, "数据解析失败");
					}
					
				}
			});
			
		}else if(resp.getResponseType().equals("QUERY_GROUP_RESP")) {
			SwingUtilities.invokeLater(new Runnable() {
				
				public void run() {
					try {
						List<JSONArray> result = ObjectUtil.getObjectByJson(resp.get("result").toString(), List.class) ;
						frame.addData(result);
					} catch (Exception e) {
						CommonDialog.showErrorMessageDialog(frame, "数据解析失败");
					}
				}
			});
		}
	}

}
